package com.kzd.sdk.ui.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Process;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;

import androidx.fragment.app.FragmentTransaction;

import com.kzd.sdk.base.OwnerActivity;
import com.kzd.sdk.callback.KZD_HttpCallback;
import com.kzd.sdk.callback.KZD_OnAccessListener;
import com.kzd.sdk.callback.KZD_OnClickListener;
import com.kzd.sdk.core.KZD_ApiConstance;
import com.kzd.sdk.core.KZD_ApiManager;
import com.kzd.sdk.core.KZD_SdkController;
import com.kzd.sdk.entity.KZD_LoginMain;
import com.kzd.sdk.entity.KZD_SdkInitParams;
import com.kzd.sdk.entity.KZD_SdkPayParams;
import com.kzd.sdk.entity.KZD_SdkRoleParams;
import com.kzd.sdk.entity.KZD_SmallGroup;
import com.kzd.sdk.entity.KZD_UserInfo;
import com.kzd.sdk.ui.fragment.KZD_AccessAgreeFragment;
import com.kzd.sdk.ui.fragment.KZD_AccessEnrollFragment;
import com.kzd.sdk.ui.fragment.KZD_AccessForgetFragment;
import com.kzd.sdk.ui.fragment.KZD_AccessLoadingFragment;
import com.kzd.sdk.ui.fragment.KZD_AccessLoginFragment;
import com.kzd.sdk.ui.fragment.KZD_AccessPhoneFragment;
import com.kzd.sdk.ui.fragment.KZD_AccessVerifyFragment;
import com.kzd.sdk.utils.AppUtils;

import java.util.List;

import static com.kzd.sdk.core.KZD_ApiConstance.KEY_ACTION_TYPE;
import static com.kzd.sdk.core.KZD_ApiConstance.KEY_ACCESS_DATA;
import static com.kzd.sdk.core.KZD_ApiConstance.KEY_USER_AGREE;

public class KZD_AccessActivity extends OwnerActivity implements KZD_OnClickListener, KZD_OnAccessListener {

    private final static int ACTION_LOGIN = 1;
    private final static int ACTION_ROLE = 2;
    private final static int ACTION_PAY = 3;

    public static void open() {
        Activity activity = KZD_SdkController.getActivity();
        if (activity == null) {
            return;
        }
        Intent intent = new Intent(activity, KZD_AccessActivity.class);
        intent.putExtra(KEY_ACTION_TYPE, ACTION_LOGIN);
        activity.startActivity(intent);
    }

    public static void openRole(KZD_SdkRoleParams roleParams) {
        Activity activity = KZD_SdkController.getActivity();
        if (activity == null) {
            return;
        }
        Intent intent = new Intent(activity, KZD_AccessActivity.class);
        intent.putExtra(KEY_ACTION_TYPE, ACTION_ROLE);
        intent.putExtra(KEY_ACCESS_DATA, roleParams);
        activity.startActivity(intent);
    }

    public static void openPay(KZD_SdkPayParams payParams) {
        Activity activity = KZD_SdkController.getActivity();
        if (activity == null) {
            return;
        }
        Intent intent = new Intent(activity, KZD_AccessActivity.class);
        intent.putExtra(KEY_ACTION_TYPE, ACTION_PAY);
        intent.putExtra(KEY_ACCESS_DATA, payParams);
        activity.startActivity(intent);
    }

    public final int frameLayoutId = 0x0000001;

    //主号登录回调信息
    private final KZD_HttpCallback<KZD_LoginMain> httpListenerLogin = new KZD_HttpCallback<KZD_LoginMain>() {
        @Override
        public void onStart() {
            showLoadingFragment();
        }

        @Override
        public void onSuccess(KZD_LoginMain data) {
            KZD_ApiManager.httpUserInfo(callbackUserInfo);
        }

        @Override
        public void onError(String error) {
            onBackPressed();
            toast(error);
        }
    };

    //用户回调信息
    private final KZD_HttpCallback<KZD_UserInfo> callbackUserInfo = new KZD_HttpCallback<KZD_UserInfo>() {

        @Override
        public void onStart() {
            showLoadingFragment();
        }

        @Override
        public void onSuccess(KZD_UserInfo data) {
            int action = getIntent().getIntExtra(KEY_ACTION_TYPE, ACTION_LOGIN);
            if (data.getVerify_info() != 1) {
                showVerifyFragment();
            } else if (!KZD_SdkController.isNotLoginSmall() && action == ACTION_ROLE) {
                KZD_SdkRoleParams roleParams = getIntent().getParcelableExtra(KEY_ACCESS_DATA);
                KZD_ApiManager.httpGameRoleUpload(roleParams, new KZD_HttpCallback<String>() {
                    @Override
                    public void onFinish(String data) {
                        finish();
                    }
                });
            } else if (!KZD_SdkController.isNotLoginSmall() && action == ACTION_PAY) {
                if (TextUtils.isEmpty(data.getMobile())) {
                    showPhoneFragment();
                    return;
                }
                KZD_SdkPayParams payParams = getIntent().getParcelableExtra(KEY_ACCESS_DATA);
                KZD_ApiManager.httpGamePayLink(payParams, new KZD_HttpCallback<String>() {
                    @Override
                    public void onSuccess(String data) {
                        KZD_WebPayActivity.open(data);
                        finish();
                    }
                });
            } else {
                KZD_ApiManager.httpSmallAccountList(new KZD_HttpCallback<List<KZD_SmallGroup>>() {
                    @Override
                    public void onFinish(List<KZD_SmallGroup> data) {
                        KZD_EnterActivity.open(data);
                        finish();
                    }
                });
            }
        }

        @Override
        public void onError(String error) {
            onBackPressed();
            toast(error);
        }
    };


    @Override
    public String getLayoutIdByName() {
        return null;
    }

    @Override
    public View getLayoutView() {
        FrameLayout frameLayout = new FrameLayout((Context) this);
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams((-1), (-1));
        frameLayout.setLayoutParams(params);
        frameLayout.setId(frameLayoutId);
        return frameLayout;
    }

    @Override
    public void initView() {
        if (KZD_SdkController.getSdkInitParams().getOrientation() == 0) {
            if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            }
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
        }
        if (KZD_SdkController.getSp().getBoolean(KEY_USER_AGREE, (false))) {
            if (KZD_SdkController.isNotLoginMain()) {
                showLoginFragment();
            } else {
                KZD_ApiManager.httpUserInfo(callbackUserInfo);
            }
        } else {
            showAgreeFragment();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        setWindow();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode != 100 || resultCode != 100) {
            return;
        }
        if (data == null) {
            return;
        }
        String uid = data.getStringExtra(KZD_ApiConstance.KEY_USER_UID_APP);
        KZD_ApiManager.httpAppAccountLogin(uid, httpListenerLogin);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == AppUtils.getId((this), "tvAccessLoginRegister")) {
            showEnrollFragment();
        } else if (v.getId() == AppUtils.getId((this), "tvAccessLoginForget")) {
            showForgetFragment();
        } else if (v.getId() == AppUtils.getId((this), "ivAccessEnrolBack")) {
            onBackPressed();
        } else if (v.getId() == AppUtils.getId((this), "ivAccessForgetBack")) {
            onBackPressed();
        } else if (v.getId() == AppUtils.getId((this), "ivAccessVerifyBack")) {
            onBackPressed();
        } else if (v.getId() == AppUtils.getId((this), "ivAccessPhoneBack")) {
            onBackPressed();
        } else if (v.getId() == AppUtils.getId((this), "tvAccessAgreeSubmit")) {
            if (KZD_SdkController.isNotLoginMain()) {
                showLoginFragment();
            } else {
                KZD_ApiManager.httpUserInfo(callbackUserInfo);
            }
        } else if (v.getId() == AppUtils.getId((this), "tvAccessAgreeExit")) {
            try {
                Thread.sleep(100);
            } catch (Exception e) {
                e.printStackTrace();
            }
            onBackPressed();
            Process.killProcess(Process.myPid());
        } else if (v.getId() == AppUtils.getId((this), "tvAccessLoginQuick")) {
            if (!AppUtils.isAppInstalled((this), KZD_ApiConstance.GT_GAME_PACKAGE)) {
                toast("未安装GT手游盒子");
            } else {
                Intent intent = new Intent();
                intent.setClassName(
                        KZD_ApiConstance.GT_GAME_PACKAGE, KZD_ApiConstance.GT_GAME_AUTH
                );
                startActivityForResult(intent, 100);
            }
        }
    }

    @Override
    public void onLoginAccount(String account, String password) {
        KZD_ApiManager.httpMainAccountLogin(account, password, httpListenerLogin);
    }

    @Override
    public void onLoginPhone(String phone, String code, String sessionId) {
        KZD_ApiManager.httpMainAccountLogin(phone, code, "1", sessionId, httpListenerLogin);
    }

    @Override
    public void onVerify(String cardName, String cardId) {
        KZD_ApiManager.httpVerifyName(cardName, cardId, callbackUserInfo);
    }

    @Override
    public void onPhone(String phone, String code, String sessionId) {
        KZD_ApiManager.httpPhoneBind(phone, sessionId, code, callbackUserInfo);
    }

    @Override
    public void onRegister(String username, String password, String code, String sessionid, String type, String name, String idcard) {
        KZD_ApiManager.httpUserRegister(username, password, code, sessionid, type, name, idcard, httpListenerLogin);
    }

    @Override
    public void onForget(String phone, String code, String sessionId, String password) {
        KZD_ApiManager.httpUserForget(phone, password, code, sessionId, new KZD_HttpCallback<String>() {

            @Override
            public void onStart() {
                showLoadingFragment();
            }

            @Override
            public void onSuccess(String data) {
                onBackPressed();
//                onBackPressed();
            }

            @Override
            public void onError(String error) {
                toast(error);
                onBackPressed();
            }
        });
    }

    private void setWindow() {
        WindowManager.LayoutParams params = getWindow().getAttributes();
        params.height = ViewGroup.LayoutParams.MATCH_PARENT;
        if (KZD_SdkController.getSdkInitParams().getOrientation() == KZD_SdkInitParams.PORTRAIT && getResources().getConfiguration().orientation
                == Configuration.ORIENTATION_PORTRAIT) {
            params.width = ViewGroup.LayoutParams.MATCH_PARENT;
        } else {
            params.width = AppUtils.getAppScreenHeight(this);
        }
        getWindow().setAttributes(params);
        getWindow().getDecorView().setBackgroundColor(Color.TRANSPARENT);
        getWindow().getDecorView()
                .setPadding((0), AppUtils.dp2px((10)), (0), AppUtils.dp2px((10)));
//        setFinishOnTouchOutside(false);
    }

    /**
     * 显示用户登录视图
     */
    private void showLoginFragment() {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        KZD_AccessLoginFragment fragment = new KZD_AccessLoginFragment();
        fragment.setOnClickListener(this);
        fragment.setOnAccessListener(this);
        transaction.replace(frameLayoutId, fragment);
        transaction.commit();
    }

    /**
     * 显示用户注册视图
     */
    private void showEnrollFragment() {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        KZD_AccessEnrollFragment fragment = new KZD_AccessEnrollFragment();
        fragment.setOnClickListener(this);
        fragment.setOnAccessListener(this);
        transaction.replace(frameLayoutId, fragment);
        transaction.addToBackStack(null);
        transaction.commit();
    }

    /**
     * 显示忘记密码视图
     */
    private void showForgetFragment() {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        KZD_AccessForgetFragment fragment = new KZD_AccessForgetFragment();
        fragment.setOnClickListener(this);
        fragment.setOnAccessListener(this);
        transaction.replace(frameLayoutId, fragment);
        transaction.addToBackStack(null);
        transaction.commit();
    }

    /**
     * 显示绑定身份认证视图
     */
    private void showVerifyFragment() {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        KZD_AccessVerifyFragment fragment = new KZD_AccessVerifyFragment();
        fragment.setOnClickListener(this);
        fragment.setOnAccessListener(this);
        transaction.replace(frameLayoutId, fragment);
        transaction.commit();
    }

    /**
     * 显示绑定手机视图
     */
    private void showPhoneFragment() {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        KZD_AccessPhoneFragment fragment = new KZD_AccessPhoneFragment();
        fragment.setOnClickListener(this);
        fragment.setOnAccessListener(this);
        transaction.replace(frameLayoutId, fragment);
        transaction.commit();
    }

    /**
     * 显示绑定身份认证视图
     */
    private void showAgreeFragment() {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        KZD_AccessAgreeFragment fragment = new KZD_AccessAgreeFragment();
        fragment.setOnClickListener(this);
        transaction.replace(frameLayoutId, fragment);
        transaction.commit();
    }

    /**
     * 显示加载视图
     */
    private KZD_AccessLoadingFragment loadingFragment;

    private void showLoadingFragment() {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if (loadingFragment == null) {
            loadingFragment = new KZD_AccessLoadingFragment();
            loadingFragment.setOnClickListener(this);
        }
        if (loadingFragment.isAdded()) {
            transaction.show(loadingFragment);
        } else {
            transaction.replace(frameLayoutId, loadingFragment);
            if (getSupportFragmentManager().getFragments().size() > 0) {
                transaction.addToBackStack(null);
            }
        }
        transaction.commit();
    }
}
